package com.asyf.provider.service.impl;

import com.asyf.provider.common.config.DataSourceKey;
import com.asyf.provider.common.config.DynamicDataSourceContextHolder;
import com.asyf.provider.service.XaService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author yjz
 * @Date 2022/2/18 11:15
 */
@Service
@Slf4j
public class XaServiceImpl implements XaService {

    @Autowired
    private NamedParameterJdbcTemplate jdbc;

    @Override
    @GlobalTransactional
    public String demo(int a) {
        insertOracleComp();
        DynamicDataSourceContextHolder.setDataSourceKey(DataSourceKey.SECONDARY);
        insertMysql();
        return null;
    }

    private void insertMysql() {
        String sql = "insert into user (id) VALUES (:id)";
        Map<String, Object> param = new HashMap<>();
        param.put("id", "1111");
        jdbc.update(sql, param);
    }

    private void insertOracleComp() {
        String sql = "insert into TEST (ID,NAME) VALUES (:id,'张三')";
        Map<String, Object> param = new HashMap<>();
        param.put("id", 1111);
        jdbc.update(sql, param);
    }
}
